package cn.android52.filepicker.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.RecyclerView
import by.kirich1409.viewbindingdelegate.viewBinding
import cn.android52.filepicker.R
import cn.android52.filepicker.databinding.FileItemBinding
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.TimeUtils
import java.io.File

class FileListAdapter : CommonAdapter<File, FileListAdapter.InnerHolder>() {

    class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val mBinding by viewBinding(FileItemBinding::bind)

        fun bind(item: File, position: Int) {
            mBinding.apply {
                val resId = if (item.isDirectory) {
                    R.drawable.format_folder
                } else {
                    R.drawable.format_other
                }
                ivIcon.setImageResource(resId)
                tvFileName.text = item.name
                tvFileDesc.text = getDesc(item)
                ivNavNext.isInvisible = item.isDirectory.not()
            }
        }

        private fun getDesc(file: File): String {
            val lastModified = TimeUtils.millis2String(FileUtils.getFileLastModified(file), "yyyy/MM/dd HH:mm")
            return when {
                file.isFile -> {
                    "${FileUtils.getSize(file)} | $lastModified"
                }

                file.isDirectory -> {
                    "${FileUtils.listFilesInDir(file).size}项 | $lastModified"
                }

                else -> lastModified
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.file_item, parent, false)
        return InnerHolder(itemView)
    }

    override fun onBindViewHolder(holder: InnerHolder, position: Int) {
        val item = getItem(position) ?: return
        holder.itemView.setOnClickListener {
            onClick(it, getItem(holder.adapterPosition), holder, position)
        }
        holder.bind(item, position)
    }
}